package com.webinsky.common.utils.db;

import java.util.ArrayList;
import java.util.List;

public class PageHelper {
	/**
	 * @param sql
	 * @param start
	 * @param size
	 * @return
	 */
	public static String startPage(String sql, int start, int size){
		if ( sql == null || sql.trim().equals("") ){
			throw new RuntimeException();
		}
		if ( start < 0 || size < 0 ){
			throw new RuntimeException();
		}
		StringBuilder sqlBuilder = new StringBuilder(sql);
		sqlBuilder.append(" limit ")
					.append(start)
						.append(",")
							.append(size);
		return sqlBuilder.toString();
	}
	/**
	 * @param sql
	 * @param page
	 * @return
	 */
	public static String startPage(String sql, Pagnation page){
		if ( sql == null ){
			throw new RuntimeException();
		}
		if ( page == null ){
			throw new RuntimeException();
		}
		StringBuilder sqlBuilder = new StringBuilder(sql);
		List<PageOrder> orders = page.getOrders();
		if ( orders != null && !orders.isEmpty() ){
			sqlBuilder.append(" order by ");
			List<String> strOrders = new ArrayList<>();
			orders.forEach(pageOrder ->{
				String field = pageOrder.getFieldName();
				String order = pageOrder.getIsAscOrDes() ? "Asc" : "Desc";
				strOrders.add(field + " " + order);
			});
			sqlBuilder.append(String.join(",", strOrders));
		}
		if ( page.getPageStart() < 0 || page.getPageSize() < 0 ){
			throw new RuntimeException();
		}
		sqlBuilder.append(" limit ")
					.append(page.getPageStart())
						.append(",")
							.append(page.getPageSize());
		return sqlBuilder.toString();
	}
}
